package com.tangyee.home_diet;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.tangyee.R;
import com.tangyee.home_diet.Uitls.HttpUitl;
import com.tangyee.home_diet.activity.RecipeDetailActivity;
import com.tangyee.home_diet.beans.Recipe;
import com.tangyee.home_diet.beans.Recipes;
import com.tangyee.refreshloadlistview.SimpleFooter;
import com.tangyee.refreshloadlistview.SimpleHeader;
import com.tangyee.refreshloadlistview.ZrcListView;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * @author: liuyaowen
 * @date: 19-2-2 上午9:49
 */

public class RecipeListFragment extends Fragment {
    private ZrcListView listView;
    private Handler handler;
    private ArrayList<RecipeListItems> msgs;
    private int pageId = -1;
    private int page = 1;
    private boolean flag = true;
    private MyAdapter adapter;
    //// 适配器里的信息
    private List<RecipeListItems> recipeListItemsList;

    public static Fragment newInstance() {
        RecipeListFragment fragment = new RecipeListFragment();
        return fragment;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View view = inflater.inflate(R.layout.layout_home_recipelist_fragment,null);
        listView = (ZrcListView) view.findViewById(R.id.zListView);
        handler = new Handler();
        recipeListItemsList = new ArrayList<>();
        // 设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(RecipeListFragment.this.getContext());
        header.setTextColor(0xff0066aa);
        header.setCircleColor(0xff33bbee);
        listView.setHeadable(header);
        // 设置加载更多的样式（可选）
        SimpleFooter footer = new SimpleFooter(RecipeListFragment.this.getContext());
        footer.setCircleColor(0xff33bbee);
        listView.setFootable(footer);
        // 设置列表项出现动画（可选）
        listView.setItemAnimForTopIn(R.anim.topitem_in);
        listView.setItemAnimForBottomIn(R.anim.bottomitem_in);
        // 下拉刷新事件回调（可选）
        listView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                refresh();
            }
        });
        // 加载更多事件回调（可选）
        listView.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                loadMore();
            }
        });
        initKnowledgeItems();
        adapter = new MyAdapter(RecipeListFragment.this.getActivity(),R.layout.layout_home_diet_recipelist_items,recipeListItemsList);
        listView.setAdapter(adapter);
        listView.refresh(); // 主动下拉刷新
        listView.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                Toast.makeText(RecipeListFragment.this.getActivity(),msgs.get(position).getTitle(),Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getActivity(), RecipeDetailActivity.class);
                intent.putExtra("recipe_image", msgs.get(position).getImageAddress());
                intent.putExtra("recipe_name", msgs.get(position).getTitle());
                intent.putExtra("production_method", msgs.get(position).getProductionMethod());
                intent.putExtra("recipe_main", msgs.get(position).getRecipeMain());
                intent.putExtra("recipe_excipient", msgs.get(position).getRecipeExcipient());
                intent.putExtra("recipe_seasoning", msgs.get(position).getRecipeSeasoning());
                intent.putExtra("tips", msgs.get(position).getTips());
                startActivity(intent);
            }
        });
        return view;
    }
    private void refresh(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                int rand = 0; // 恒等于0，每次刷新成功
                if(rand == 0 || pageId == -1){
                    pageId = 0;
                    // 每次刷新都将重置以前加载的数据
                    msgs = new ArrayList<RecipeListItems>();
                    // 每次刷新成功，msgs都将增加6个item，knowledgeItemList的大小不变，变得时msgs的大小
                    for(RecipeListItems items : recipeListItemsList){
                        msgs.add(items);

                    }

                    adapter.notifyDataSetChanged();
                    listView.setRefreshSuccess("加载成功"); // 通知加载成功
                    listView.startLoadMore(); // 开启LoadingMore功能
                }else{
                    listView.setRefreshFail("加载失败");
                }
            }
        }, 2 * 1000);
    }
    private void loadMore(){

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
//                pageId++;
//                // 最多加载6次
//                if(pageId < recipeListItemsList.size()){
//                    for(RecipeListItems items:recipeListItemsList){
//                        msgs.add(items);
//                    }
//                    adapter.notifyDataSetChanged();
//                    listView.setLoadMoreSuccess();
//                }else{
//                    listView.stopLoadMore();
//                }
                if (flag == true) {
                    loadRecipeItem();
                    msgs = new ArrayList<>();
                    for (RecipeListItems items : recipeListItemsList) {
                        msgs.add(items);
                    }
                    adapter.notifyDataSetChanged();
                    listView.setLoadMoreSuccess();
                } else {
                    listView.stopLoadMore();
                }

            }
        }, 2 * 1000);
    }
    private void initKnowledgeItems(){

        loadRecipeItem();
//        for (int i = 0;i < 10;i++){
//            RecipeListItems item = new RecipeListItems("东坡肉",R.drawable.foodimage,2,"20","300");
//            recipeListItemsList.add(item);
//        }
    }

    private void loadRecipeItem() {
        //Log.d("mmp", "loadRecipeItem前" + String.valueOf(page));
        String address = "https://www.tangyee.com/Mobile/Recipe/GetRecipes?pagesize=16&page=" + page;
        HttpUitl.sendOkHttpRequest(address, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Gson gson = new Gson();
                String responseString = response.body().string();
                if (responseString.equals("[]")) {
                    flag = false;
                }
                try {
                    JSONArray jsonArray = new JSONArray(responseString);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        String recipe1 = jsonArray.getJSONObject(i).toString();
                        Recipes recipes = gson.fromJson(recipe1, Recipes.class);
                        Recipe recipe = recipes.getRecipe();
                        String imgAddress = "https://www.tangyee.com/Content/upload/images/RecipeImages/" + recipes.getImage();
                        RecipeListItems item = new RecipeListItems(recipe.getRecipeName(), imgAddress, recipe.getPepperLevel(), "20", "300",
                                recipe.getMethod(),recipe.getMain(),recipe.getAccessory(), recipe.getSeasoning(),recipe.getTips());
                        recipeListItemsList.add(item);
                    }
                    page++;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }
    // 列表的适配器
    private class MyAdapter extends BaseAdapter {
        // 上下文
        private Context context;
        // 菜谱的布局id
        private int recipeListItemLayoutId;
        // 菜谱列表
        private List<RecipeListItems> recipeListItemsList;
        public MyAdapter(Context context, int recipeListId, List<RecipeListItems> objects){
            this.context = context;
            this.recipeListItemLayoutId = recipeListId;
            this.recipeListItemsList = objects;
        }
        @Override
        public int getCount() {
            return msgs==null ? 0 : msgs.size();
        }
        @Override
        public Object getItem(int position) {
            return msgs.get(position);
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = LayoutInflater.from(context).inflate(this.recipeListItemLayoutId, null);
            RecipeListItems item = msgs.get(position);
            TextView title = view.findViewById(R.id.recipetitle);
            ImageView imageView = view.findViewById(R.id.recipeimg);
            TextView like = view.findViewById(R.id.like);
            TextView collection = view.findViewById(R.id.collection);
            ImageView star = view.findViewById(R.id.star);
            ImageView star1 = view.findViewById(R.id.star1);
            ImageView star2 = view.findViewById(R.id.star2);
            title.setText(item.getTitle());
            Glide.with(context)
                    .load(item.getImageAddress())
                    .into(imageView);
            //imageView.setImageResource(item.getImageId());
            if(item.getCount() == 2){
                star.setImageResource(R.drawable.star);
            }else if(item.getCount() == 1){
                star.setImageResource(R.drawable.star);
                star1.setImageResource(R.drawable.star);
            }else if(item.getCount() == 0){
                star.setImageResource(R.drawable.star);
                star1.setImageResource(R.drawable.star);
                star2.setImageResource(R.drawable.star);
            }
            like.setText(item.getLike());
            collection.setText(item.getCollection());
            return view;
        }
    }
    // 每一条的菜谱的信息
    private class RecipeListItems{
        // 菜谱的标题
        private String title;
        // 菜谱的图片信息，这里是图片的地址
        private String imageAddress;
        //星星个数
        private int count;
        // 菜谱喜欢人数
        private String like;
        //菜谱搜集的人数
        private String collection;
        //菜谱制作方法
        private String productionMethod;
        //菜谱主料
        private String recipeMain;
        //菜谱辅料
        private String recipeExcipient;
        //菜谱调料
        private String recipeSeasoning;
        //小技巧
        private String tips;
        public RecipeListItems(String title,String imageAddress,int count,String like,String collection, String method,
                               String recipeMain, String recipeExcipient, String recipeSeasoning, String tips){
            this.title = title;
            this.imageAddress = imageAddress;
            this.count = count;
            this.like = like;
            this.collection = collection;
            this.productionMethod = method;
            this.recipeMain = recipeMain;
            this.recipeExcipient = recipeExcipient;
            this.tips = tips;
        }

        public int getCount(){
            return count;
        }

        public void setCount(){
            this.count=count;
        }

        public String getLike(){
            return like;
        }
        public void setLike(){
            this.like=like;
        }

        public String getCollection(){
            return collection;
        }

        public  void setCollection(){
            this.collection=collection;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getImageAddress() {
            return imageAddress;
        }

        public void setImageAddress(String imageAddress) {
            this.imageAddress = imageAddress;
        }

        public String getProductionMethod() {
            return productionMethod;
        }

        public void setProductionMethod(String productionMethod) {
            this.productionMethod = productionMethod;
        }

        public String getRecipeMain() {
            return recipeMain;
        }

        public void setRecipeMain(String recipeMain) {
            this.recipeMain = recipeMain;
        }

        public String getRecipeExcipient() {
            return recipeExcipient;
        }

        public void setRecipeExcipient(String recipeExcipient) {
            this.recipeExcipient = recipeExcipient;
        }

        public String getRecipeSeasoning() {
            return recipeSeasoning;
        }

        public void setRecipeSeasoning(String recipeSeasoning) {
            this.recipeSeasoning = recipeSeasoning;
        }

        public String getTips() {
            return tips;
        }

        public void setTips(String tips) {
            this.tips = tips;
        }
    }

}
